package com.qiaoas.springbootjdbctemplate.Dao.impl;

import com.qiaoas.springbootjdbctemplate.Bean.User;
import com.qiaoas.springbootjdbctemplate.Dao.UserDao;
import com.qiaoas.springbootjdbctemplate.Mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import java.sql.Types;
import java.util.List;
import java.util.Map;

@Repository("userDao")
public class UserDaoImp implements UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;


    @Override
    public int insert(User user) {
        String sql = "insert into user(no,name,age) values (:no,:name,:age)";
        NamedParameterJdbcTemplate npjt = new NamedParameterJdbcTemplate(this.jdbcTemplate.getDataSource());
        return npjt.update(sql,new BeanPropertySqlParameterSource(user));
    }

    @Override
    public int update(User user) {
        String sql = "update user set name = ?, age = ? where no = ?";
        Object[] args = { user.getName(), user.getAge(), user.getNo() };
        int[] argTypes = {Types.VARCHAR, Types.INTEGER, Types.INTEGER };
        return this.jdbcTemplate.update(sql, args, argTypes);
    }

    @Override
    public int delete(User user) {
        String sql = "delete from user where no = ?";
        Object[] args = { user.getNo() };
        int[] argTypes = { Types.INTEGER };
        return this.jdbcTemplate.update(sql, args, argTypes);
    }

    @Override
    public User selete(int no) {
        String sql = "select * from user where no = ?";
        Object[] args = { no };
        int[] argsType = { Types.INTEGER };
        List<User> userList = this.jdbcTemplate.query(sql,args,argsType, new UserMapper());
        if (userList != null && userList.size() > 0){
            return userList.get(0);
        } else {
            return null;
        }
    }

    @Override
    public List<Map<String, Object>> userList() {
        String sql = "select * from user";
        return this.jdbcTemplate.queryForList(sql);
    }



}
